﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
namespace DotNet.Utilities
{
    /// <summary>
    /// 提供操作文件的常用方法
    /// </summary>
    public class FileUtil
    {
        /// <summary>
        /// 读取文件（默认编码）
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string Read(string path)
        {
            return Read(path, Encoding.Default);
        }
        /// <summary>
        /// 读取文件（指定编码）
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public static string Read(string path, Encoding encode)
        {
            FileStream fs = null;
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    break;
                }
                catch
                {
                    System.Threading.Thread.Sleep(50);
                }
            }
            if (fs == null) return "";
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(fs, encode);
                return sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sr.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 返回文件行的数组
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string[] ReadLines(string path)
        {
            return ReadLines(path, Encoding.Default);
        }
        /// <summary>
        /// 返回文件行的数组
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public static string[] ReadLines(string path, Encoding encode)
        {
            try
            {
                return File.ReadAllLines(path, encode);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 向文件写入内容（默认编码）
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public static bool Write(string path, string content)
        {
            return Write(path, content, Encoding.Default);
        }
        /// <summary>
        /// 向文件写入内容（指定编码）
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static bool Write(string path, string content, Encoding encode)
        {
            FileStream fs = null;
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                    break;
                }
                catch
                {
                    System.Threading.Thread.Sleep(50);
                }
            }
            if (fs == null) return false;
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(fs, encode);
                sw.Write(content);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 向文件追加内容（默认编码）
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public static bool Append(string path, string content)
        {
            return Append(path, content, Encoding.Default);
        }
        /// <summary>
        /// 向文件追加内容（指定编码）
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="content">内容</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static bool Append(string path, string content, Encoding encode)
        {
            FileStream fs = null;
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    break;
                }
                catch
                {
                    System.Threading.Thread.Sleep(50);
                }
            }
            if (fs == null) return false;
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(fs, encode);
                sw.Write(content);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static bool Delete(string path)
        {
            try
            {
                File.Delete(path);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取指定目录下所有文件
        /// </summary>
        /// <param name="dir">目录</param>
        /// <returns></returns>
        public static string[] GetFiles(string dir)
        {
            try
            {
                return Directory.GetFiles(dir);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取目录中所有文件路径
        /// </summary>
        /// <param name="dir">目录</param>
        /// <param name="patt">匹配正则(如：*.(txt|log))</param>
        /// <returns></returns>
        public static string[] GetFiles(string dir, string patt)
        {
            string pattern = "(?i)^" + patt.Replace(".", @"\.") + "$";

            Regex reg = new Regex(pattern);

            List<string> list = new List<string>();

            try
            {
                string[] files = Directory.GetFiles(dir);

                foreach (string file in files)
                {
                    if (reg.IsMatch(file))
                        list.Add(file);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list.ToArray();
        }
        /// <summary>
        /// 得到文件的内容的集合 适用于 .csv .txt文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<string[]> GetFileContentByLinq(string path,char[] sprated)
        {
            var q1 = File.ReadAllLines(path).Select(l => l.Split(sprated)).ToList();
            return q1;
            //var q2 = from l in File.ReadAllLines(path)
            //         select l.Split(',');

        }
    }
}
